package com.hz.web.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.digest.DigestUtils;

/**
 * 数据校验
 * 
 * 消息摘要算法[散列算法] MD(Message Digest)[消息摘要算法]、SHA-1(Secure Hash
 * Algorithm)[安全散列算法]、HamcMD5(Message Authentication Code)[消息认证码算法]、MAC( )
 * 
 * @author sdl
 * 
 */
public class MD5Utils {

	private final static String MD_INSTANCE = "MD5";
	private final static String ENCODING = "UTF-8";
	
	/**
	 * md5加密
	 * @param source
	 * @return
	 */
	public static byte[] encodeMD5(byte[] source) {
		byte[] dest = null;
		try {
			MessageDigest md = MessageDigest.getInstance(MD_INSTANCE);
			dest = md.digest(source);
			
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		
		return dest;
	}

	/**
	 * 生成md5 校验码
	 * @param source
	 * @return
	 */
	public static String md5HexString(String source){
		return DigestUtils.md5Hex(encodeMD5(source.getBytes()));
		
	}
	
	public static String getMD5Str(String str)  
    {  
        MessageDigest messageDigest = null;  
        try  
        {  
            messageDigest = MessageDigest.getInstance("MD5");  
            messageDigest.reset();  
            messageDigest.update(str.getBytes("UTF-8"));  
        } catch (NoSuchAlgorithmException e)  
        {  
            System.out.println("NoSuchAlgorithmException caught!");  
            System.exit(-1);  
        } catch (UnsupportedEncodingException e)  
        {  
            e.printStackTrace();  
        }  
  
        byte[] byteArray = messageDigest.digest();  
  
        StringBuffer md5StrBuff = new StringBuffer();  
  
        for (int i = 0; i < byteArray.length; i++)  
        {  
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)  
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));  
            else  
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));  
        }  
        return md5StrBuff.toString();  
    }  

}
